/**
 * 
 */
package net.entelijan.cobean.filesel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class FileselComboBoxModel extends AbstractListModel implements ComboBoxModel {

	private static Log log = LogFactory.getLog(FileselComboBoxModel.class);

	private static final long serialVersionUID = 1L;
	private LinkedList<String> items;
	private String selectedItem;
	private int maxLength;

	public FileselComboBoxModel(Collection<String> items, int maxLength) {
		this.items = new LinkedList<String>(items);
		this.maxLength = maxLength;
	}

	public Object getSelectedItem() {
		return this.selectedItem;
	}

	public void setSelectedItem(Object anItem) {
		if (anItem != null) {
			if (!(anItem instanceof String)) {
				throw new IllegalArgumentException(
						"You can only use strings for "
								+ this.getClass().getName());
			}
			String sItem = (String) anItem;
			log.debug("[setSelectedItem] sItem:'" + sItem + "' selectedItem:'"
					+ selectedItem + "'");
			if ((selectedItem != null && !selectedItem.equals(anItem))
					|| selectedItem == null) {
				items.remove(anItem);
				items.remove(selectedItem);
				if (selectedItem != null) {
					items.addFirst(selectedItem);
				}
				while (items.size() > maxLength) {
					items.removeLast();
				}
				selectedItem = sItem;
				fireContentsChanged(this, -1, -1);
			}
		}
	}

	public Object getElementAt(int index) {
		return items.get(index);
	}

	public int getSize() {
		return items.size();
	}

	public Collection<String> getValuesToStore() {
		ArrayList<String> re = new ArrayList<String>();
		if (selectedItem != null) {
			re.add(selectedItem);
		}
		for (int i = 0; i < items.size(); i++) {
			String item = this.items.get(i);
			if (item != null && item.length() > 0) {
				re.add(item);
			}
		}
		return re;
	}

}